package com.foreknow.service.impl;

import com.foreknow.dao.impl.AdminDaoImpl;
import com.foreknow.dao.impl.RegisterDaoImpl;
import com.foreknow.db.DBManager;
import com.foreknow.model.Admin;
import com.foreknow.service.RegisterService;

import javax.swing.*;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class RegisterServiceImpl implements RegisterService {
    private DBManager db;
    private Connection conn = null;
    private RegisterDaoImpl rdao = new RegisterDaoImpl();

    @Override
    public boolean register(String adminName, String password) {
        db = DBManager.getInstance();
        conn=db.getConnection();
        rdao.setConnection(conn);
        try {
            JOptionPane jpane = new JOptionPane();
            List<Object> admins = rdao.getAll();
            List<String> adminList = new ArrayList<>();
            int j = 0;
            int i = 0;
            for (Object admin : admins){
                Admin admin1 = (Admin) admin;
                adminList.add(admin1.getAdminName());
            }
            while (i<adminList.size()) {
                if (adminList.get(i).equals(adminName)){
                    j=0;
                    break;
                }else if (!adminList.get(i).equals(adminName) && i<adminList.size()){
                    j=1;
                    i++;
                }
            }
            if (j==0){
                JOptionPane.showMessageDialog(jpane, "用户名已存在，请重新输入！", "提示", JOptionPane.WARNING_MESSAGE);
                return false;
            }else {
                rdao.setNamePsw(adminName,password);
                conn.commit();
                JOptionPane.showMessageDialog(jpane, "注册成功！", "提示", JOptionPane.WARNING_MESSAGE);
                return true;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return false;
    }
}
